<template>
  <div></div>
</template>

<script>
import WebsocketHeartbeatJs from "websocket-heartbeat-js";
import { get_broker } from "@/assets/js/API/market.js";
export default {
  data() {
    return {
      websocketHeartbeatJs: null, // websocket初始化值
      tradeWSList: [], // 交易ws列表数据
      reWsSub: [], // 股票订阅数据
      brokerList: [], // 券商数据
    };
  },
  created() {
    this.websock();
    this.getBrokersList();
  },
  mounted() {},
  computed: {
    StockData() {
      return this.$store.state.index.StockData;
    },
    level() {
      return this.$store.state.index.level;
    },
    symbolSub() {
      // 订阅的股票请求
      return this.$store.state.wsModel.symbolSub;
    },
    zixuanSub() {
      // 订阅的自选请求
      return this.$store.state.wsModel.zixuanSub;
    },
    wsDapanList() {
      // 订阅的大盘请求
      return this.$store.state.wsModel.wsDapanList;
    },
    wsMarket() {
      // 单一市场当前页面所有股票的推送
      return this.$store.state.wsModel.wsMarket;
    },
  },
  watch: {
    // 当存在单独股票市场的订阅列表时开启订阅功能
    wsMarket: {
      handler(val, old) {
        var _this = this;
        if (old != "") {
          // 存在旧的单一股票市场的订阅，先取消再订阅
          if (_this.websocketHeartbeatJs != null) {
            if (_this.websocketHeartbeatJs.delSubscribe) {
              _this.websocketHeartbeatJs.delSubscribe(old);
            }
          }
        }
        if (_this.websocketHeartbeatJs != null) {
          if (_this.websocketHeartbeatJs.delSubscribe) {
            _this.websocketHeartbeatJs.webSocketOpen(val);
          }
        }
      },
      deep: true,
    },
    // 当存在大盘订阅列表时开启订阅功能
    wsDapanList: {
      handler(val) {
        if (val.length > 0) {
          if (this.websocketHeartbeatJs != null) {
            this.websocketHeartbeatJs.webSocketOpen(val);
          }
        }
      },
      deep: true,
    },
    StockData: {
      handler(val) {
        var _this = this;
        // 已订阅当前股票要先取消订阅再重新订阅
        if (_this.symbolSub != "") {
          if (_this.websocketHeartbeatJs != null) {
            if (_this.websocketHeartbeatJs.delSubscribe) {
              _this.websocketHeartbeatJs.delSubscribe(_this.symbolSub);
              let list = _this.getList(val, _this.level);
              _this.websocketHeartbeatJs.webSocketOpen(list);
            }
          }
        } else {
          if (_this.websocketHeartbeatJs != null) {
            let list = _this.getList(val, _this.level);
            _this.websocketHeartbeatJs.webSocketOpen(list);
          }
        }
        _this.$forceUpdate();
      },
      deep: true,
    },
    zixuanSub: {
      handler(val, old) {
        var _this = this;
        if (old != "") {
          // 存在旧的自选订阅，先取消再订阅
          if (_this.websocketHeartbeatJs != null) {
            if (_this.websocketHeartbeatJs.delSubscribe) {
              _this.websocketHeartbeatJs.delSubscribe(old);
            }
          }
        }
        if (_this.websocketHeartbeatJs != null) {
          if (_this.websocketHeartbeatJs.webSocketOpen) {
            _this.websocketHeartbeatJs.webSocketOpen(val);
          }
        }
      },
      deep: true,
    },
    deep: true,
  },
  methods: {
    // 获取券商名称列表
    async getBrokersList() {
       const res = await get_broker();
      if (res.code != 1) return this.$message.error(res.msg);
      let list = res.data.list;
      let len = list.length;
      let arr = [];
      for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
          if (list[i].brokerId == list[j].brokerId ) {
            i++
            j=i;
          }
        }
        arr.push(list[i]);
      }
      this.brokerList = arr;
    },
    // 推送参数设置
    setOption() {
      const protocol = window.location.protocol == "http:" ? "ws://" : "wss://";
      const options = {
        url:
          protocol +
          window.g.wsURL +
          "?token=" +
          sessionStorage.getItem("token"),
        pingTimeout: 15000,
        pongTimeout: 10000,
        reconnectTimeout: 10000,
        pingMsg: '{"action":"PING"}',
      };
      let websocketHeartbeatJs = new WebsocketHeartbeatJs(options);
      return websocketHeartbeatJs;
    },
    // 将逐笔，盘口，行情加入队列
    queue(val) {
      let que = [];
      let val1 = {
        market: val.market,
        securityType: val.securityType,
        action: "Q",
        symbol: val.symbol,
      };
      que.push(val1);
      let val2 = JSON.parse(JSON.stringify(val1));
      val2.action = "T";
      que.push(val2);
      let val3 = JSON.parse(JSON.stringify(val1));
      val3.action = "O";
      que.push(val3);
      let val4 = JSON.parse(JSON.stringify(val1));
      val4.action = "B";
      que.push(val4);
      this.$store.dispatch("SetSymbolSub", JSON.stringify(que));
      return que;
    },
    getList(val, level) {
      let list = [];
      // 沪深行情大于lv1等级实时推送
      if (level.CN.level > 1) {
        // 当前股票是沪深的股票
        if (val.market == "SSE" || val.market == "SZSE") {
          list = this.queue(val);
          return list;
        }
      }
      // 港股行情等级大于LV1实时推送
      if (level.HK.level > 1) {
        if (val.market == "HKEX") {
          list = this.queue(val);
          return list;
        }
      }
      // 美股行情等级大于LV0实时推送
      if (level.US.level > 0) {
        if (val.market == "US") {
          list = this.queue(val);
          return list;
        }
      }
      return list;
    },
    // 拼接取消订阅数据类型
    SubData(val) {
      if (val == "") return;
      if (typeof val == "string") val = JSON.parse(val);
      let values = val;
      let items = "";
      for (let i = 0; i < values.length; i++) {
        let objJoin = "";
        for (let key in values[i]) {
          if (key != "symbol") objJoin = objJoin + values[i][key] + "|";
          else objJoin = objJoin + values[i][key];
        }
        if (i != values.length - 1) items = items + objJoin + ",";
        else items = items + objJoin;
      }
      return items;
    },
    // ws订阅类型过滤器
    wsFifters(action, val) {
      // T:交易数据 Q:行情数据 O:盘口数据
      if (val == "") return;
      let vals = val.split("|");
      // Q:行情数据
      if (action == "Q") {
        if (vals[1] != 1) {
          if (this.wsMarket != "") {
            let data = JSON.parse(this.wsMarket);
            for (let item of data) {
              // 如果股票代码与大盘推送列表相同放入推送列表
              if (item.symbol == vals[3]) {
                this.$store.dispatch("SetDaPanDetail", JSON.stringify(vals));
                break;
              }
            }
          }
        }
        // 当前股票推送
        if (JSON.stringify(this.StockData) != "{}") {
          if (
            this.StockData.symbol == vals[3] &&
            this.StockData.market == vals[0] &&
            this.StockData.securityType == vals[1]
          ) {
            this.$store.dispatch("SetQuotation", JSON.stringify(vals));
          }
        }
        // 自选股票推送
        if (this.zixuanSub) {
          // 按自选顺序将股票信息存入自选列表
          let zixuan = JSON.parse(this.zixuanSub);
          for (let i = 0; i < zixuan.length; i++) {
            // 如果当前过滤值与自选列表股票代码相同存入自选队列
            if (
              zixuan[i].symbol == vals[3] &&
              zixuan[i].market == vals[0] &&
              zixuan[i].securityType == vals[1]
            ) {
              this.$nextTick(() => {
                this.$set(zixuan[i], "latestPrice", vals[4]);
                this.$set(zixuan[i], "high", vals[5]);
                this.$set(zixuan[i], "open", vals[6]);
                this.$set(zixuan[i], "low", vals[7]);
                this.$set(zixuan[i], "close", vals[8]);
                this.$set(zixuan[i], "volume", vals[9]);
                this.$set(zixuan[i], "amount", vals[10]);
                this.$set(zixuan[i], "gain", (vals[4] - vals[8]) / vals[8]);
                this.$store.dispatch("SetZixuanList", JSON.stringify(zixuan));
              });
              break;
            }
          }
        }
        // 市场股推送
        if (this.wsMarket) {
          // 将市场股票信息存入市场列表列表
          let marketList = JSON.parse(this.wsMarket);
          for (let i = 0; i < marketList.length; i++) {
            // 如果当前过滤值与自选列表股票代码相同存入自选队列
            if (
              marketList[i].symbol == vals[3] &&
              marketList[i].market == vals[0] &&
              marketList[i].securityType == vals[1]
            ) {
              this.$nextTick(() => {
                this.$set(marketList[i], "latestPrice", vals[4]);
                this.$set(marketList[i], "high", vals[5]);
                this.$set(marketList[i], "open", vals[6]);
                this.$set(marketList[i], "low", vals[7]);
                this.$set(marketList[i], "close", vals[8]);
                this.$set(marketList[i], "volume", vals[9]);
                this.$set(marketList[i], "amount", vals[10]);
                this.$set(marketList[i], "gain", (vals[4] - vals[8]) / vals[8]);
                this.$store.dispatch(
                  "SetWsMarketInfo",
                  JSON.stringify(marketList)
                );
              });
              break;
            }
          }
        }
      } else if (action == "T") {
        // 交易推送数据
        if (
          this.StockData.symbol == vals[3] &&
          this.StockData.market == vals[0]
        ) {
          if (this.tradeWSList.length == 20) {
            let tradeData = JSON.stringify(this.tradeWSList);
            this.$store.dispatch("SetTransaction", tradeData);
            this.tradeWSList = [];
          } else this.tradeWSList.unshift(vals);
        }
      } else if (action == "O") {
        this.$store.dispatch("SetPankou", JSON.stringify(vals));
      } else if (action == "B") {
        this.BFifter(vals);
      }
    },
    // 买卖经济过滤
    BFifter(vals) {
      if (vals.length > 0) {
        let buyLength = 2 * vals[3] + 3;
        let buyObj = [];
        let sellObj = [];
        // this.pushArray(3,buyLength, vals);
        buyObj = this.pushArray(3, buyLength, vals);
        sellObj = this.pushArray(buyLength + 1, vals.length - 1, vals);
        this.$store.dispatch("SetBuyWs", buyObj);
        this.$store.dispatch("SetSellWs", sellObj);
        // console.log(vals,buyObj,sellObj,"队列推送")
      }
    },
    pushArray(start, end, vals) {
      let obj = {
        brokerId: "",
        status: 0,
      };
      let arr = [
        {
          list: [],
          level: "",
        },
        {
          list: [],
          level: "",
        },
        {
          list: [],
          level: "",
        },
      ];
      for (let i = start; i <= end - 1; i = i + 2) {
        obj = {
          brokerId: vals[i + 1],
          status: vals[i + 2],
          brokerName: "",
          brokerNameEn: ""
        };
        for(let e of this.brokerList){
          if(e.brokerId == obj.brokerId) {
            obj.brokerName = e.nameZh;
            obj.brokerNameEn = e.nameEn;
            break;
          }
        };
        if(arr[vals[i + 2] - 1] && arr[vals[i + 2] - 1].hasOwnProperty("list")) {
          arr[vals[i + 2] - 1].list.push(obj);
          arr[vals[i + 2] - 1].level = vals[i + 2];
        }
      }
      return arr;
    },
    websock() {
      // 推送初始化
      this.websocketHeartbeatJs = this.setOption();
      // 得到对应格式的WS订阅数据列表
      // 打开ws时的回调
      // 取消订阅
      this.websocketHeartbeatJs.delSubscribe = (val) => {
        // 发送关闭请求
        if (typeof val == "string") val = JSON.parse(val);
        let vals = this.reWsSub;
        for (let i = 0; i < val.length; i++) {
          for (let j = 0; j < vals.length; j++) {
            if (
              val[i].symbol == vals[j].symbol &&
              val[i].action == vals[j].action
            )
              this.reWsSub.splice(j, 1);
          }
        }
        let items = this.SubData(val);
        let value = {
          action: "DELSUBSCRIBE",
          symbols: items,
        };
        this.websocketHeartbeatJs.send(JSON.stringify(value));
        this.tradeWSList = [];
      };
      // 发送订阅请求
      this.websocketHeartbeatJs.webSocketOpen = (val) => {
        if (typeof val == "string") val = JSON.parse(val);
        if (val.length <= 0) return;
        let vals = this.reWsSub;
        if (vals.length == 0) this.reWsSub = val;
        else {
          for (let i = 0; i < val.length; i++) {
            for (let j = 0; j < vals.length; j++) {
              if (
                val[i].symbol == vals[j].symbol &&
                val[i].action == vals[j].action
              )
                break;
              if (j == vals.length - 1) this.reWsSub.push(val[i]);
            }
          }
        }
        let items = this.SubData(val);
        let value = {
          action: "SUBSCRIBE",
          symbols: items,
        };
        this.websocketHeartbeatJs.send(JSON.stringify(value));
        console.log(value, "connect success");
      };
      this.websocketHeartbeatJs.onopen = () => {
        // 得到当前股票订阅格式
        // this.reWsSub = data;
        // this.websocketHeartbeatJs.webSocketOpen(data);
      };
      // 接收到数据，过滤数据
      this.websocketHeartbeatJs.onmessage = (e) => {
        e = JSON.parse(e.data);
        // 如果返回连接成功，开始订阅
        if (e.action == "OPENED") {
          if (this.StockData != "") {
            let list = this.getList(this.StockData, this.level);
            this.websocketHeartbeatJs.webSocketOpen(list);
          }
          if (this.zixuanSub != "") {
            this.websocketHeartbeatJs.webSocketOpen(this.zixuanSub);
          }
          if (this.wsDapanList.length > 0) {
            this.websocketHeartbeatJs.webSocketOpen(this.wsDapanList);
          }
          if (this.wsMarket != "") {
            this.websocketHeartbeatJs.webSocketOpen(this.wsMarket);
          }
        }
        if (e.action == "PING") {
          // 心跳重连成功重新订阅
          if (this.StockData != "") {
            let list = this.getList(this.StockData, this.level);
            this.websocketHeartbeatJs.webSocketOpen(list);
          }
          if (this.zixuanSub != "") {
            this.websocketHeartbeatJs.webSocketOpen(this.zixuanSub);
          }
          if (this.wsDapanList.length > 0) {
            this.websocketHeartbeatJs.webSocketOpen(this.wsDapanList);
          }
          if (this.wsMarket != undefined && this.wsMarket != "") {
            this.websocketHeartbeatJs.webSocketOpen(this.wsMarket);
          }
          // this.websocketHeartbeatJs.webSocketOpen(list);
          // this.websocketHeartbeatJs.webSocketOpen(this.reWsSub);
        }
        if (e.data != undefined) {
          if (e.action == "DELSUBSCRIBE") {
            // 如果取消全部订阅，关闭连接
            return;
          }
          // 分发数据
          this.wsFifters(e.action, e.data);
        }
      };
      this.websocketHeartbeatJs.onreconnect = (e) => {
        console.log("reconnecting...");
      };
      this.websocketHeartbeatJs.onclose = (e) => {
        this.websocketHeartbeatJs.close();
        console.log("connect close");
      };
      this.$store.dispatch("SETHEARTBEAT", this.websocketHeartbeatJs);
    },
  },
};
</script>

<style lang="less">
</style>